<?php

namespace AuctionBack\Controller;

use AuctionCore\Common\Page;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\CarResource\Car;
use AuctionCore\Finance\Loan;
use AuctionCore\Finance\Collection;
use AuctionCore\ChangeOrder\ChangeOrder;
use AuctionCore\CarDealer\Dealer;
use Think\Log;

/**
 * 车商付款跟踪
 */
class PayTrackController extends BaseController
{

    public function __construct()
    {
        parent::__construct();
        $this->emp_id = $this->user_info['emp_id'];
    }

    //待收付款
    public function pay_index()
    {
        //付款状态
        $this->assign('dealer_pay_mode',C('DEALER_PAY_MODE'));
        //待收车款 - 收款状态
        $this->assign('collection_status_wait',array_slice(C('COLLECTION_STATUS'), 0, 2, true));
        //核实车款 -- 收款状态
        $this->assign('collection_status_verify',array_slice(C('COLLECTION_STATUS'), 2, 2, true));
        //收款失败 -- 收款状态
        $this->assign('collection_status_failed',array_slice(C('COLLECTION_STATUS'), 4, 2, true));
        $this->display();
    }

    //付款列表
    public function pay_list()
    {
        $page = I("get.p", 1);
        $size = 10;
        $status = I("request.status/d",1);
        $location_area = I('request.la/d', 0);
        $keyword = I("request.keyword/s", '','trim');
        $pay_mode = I("request.pay_mode/d", '');
        $pay_status = I("request.pay_status/d", '');
        $params = [
            'status' => $status,
            'keyword' => $keyword,
            'pay_mode' => $pay_mode,
            'pay_status' => $pay_status
        ];
        if ($location_area == 0) {
            $params['location_area'] = $this->user_info['bc_code'];
        } else {
            $params['location_area'] = [$location_area];
        }

        $rc = new Collection();
        $result = $rc->pay_track_list($page, $size, $params);
        $total = $result['total'] > 0 ? $result['total'] : 0;
        $list = !empty($result['list']) ? $result['list'] : [];
        //分页
        $Page = new \AuctionCore\Common\AjaxPage($total, $size, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %nextPage% %downPage%  %end% %jumpform%");

        //        dump($list);
        $show = $Page->show();          // 分页显示输出
        $this->assign('page', $show);   // 赋值分页输出
        $this->assign('list', $list);
        $this->assign('params', $params);
        $this->assign('p', $page);
        $this->assign('status', $status);
        $this->assign('location_area', $location_area);
        $this->display();

    }

    /**
     * 车商付款跟踪
     */
    public function dealer_pay_track(){
        $order_id = I("get.id/d");
        //获取订单信息
        $o = new AuOrder($order_id);
        $order = $o->detail();
        if($order['dealer_pay_mode'] == 2){
            $loan = new Loan();
            $loan_detail = $loan->get_loan_detail($order_id);
            $this->assign('loan_detail', $loan_detail);
        }
         //车商id
        $dealer_id = !empty($order['success_dealer_id']) ? $order['success_dealer_id'] : 0;
        $dealer = new Dealer($dealer_id);
        $dealerInfo = $dealer->baseInfo();
         //获取车信息
        $car = \AuctionCore\CarResource\Car::getDetailWithChannel($order['car_id']);
        $car['emission'] = C('EMISSION.' . $car['emission']);
        $car['pointer_mileage'] = formatMileage($car['pointer_mileage']);
        //获取车辆补充说明
        $car['other_info'] = M("car_perform")->where('car_id='.$order['car_id'])->getField("other_info");

        $show_from = \AuctionCore\Other\Channel::get_from();  //获取渠道来源信息
        $this->assign('show_from', $show_from);
         //获取车型车牌信息
        $cm = new \AuctionCore\CarResource\CarModel();
        $brand = $cm->get_model_by_id($car['brand_id'], 'brand');
        $series = $cm->get_model_by_id($car['series_id'], 'series');
        $model = $cm->get_model_by_id($car['model_id']);
        $car['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        $car['plate'] = C("PLATE_PREFIX." . $car['plate_prefix']) . $car['plate_suffix'];
        //获取年检有效期
        $procedure = $cm->get_procedure_by_car_id($order['car_id']);
        $city = new \AuctionCore\Other\Address();
        $location_area = $city->get_name_by_code($car['location_area']);
        $car['reg_city'] = $city->get_name_by_code($car['reg_city']);
        $car['verify_expiry'] = $procedure['verify_expiry'];
        $car['com_insure_expiry'] = $procedure['com_insure_expiry'];
        $car['ill_deduc_point'] = $procedure['ill_deduc_point'];
        $car['forfeit'] = $procedure['forfeit'];
        //跟踪日志
        $follow_log = $o ->get_dealer_pay_follow_log($order_id);
        $transfer_type = C('TRANSFER_LIMIT');
        //收款明细
        $orderFee = AuOrder::getOrderFee($order_id);
        $this->assign('order_fee',$orderFee);
        $this->assign('transfer_type', $transfer_type);
        $this->assign('location_area', $location_area);
        $this->assign('order', $order);
        $this->assign('car', $car);
        $this->assign('dealer', $dealerInfo);
        $this->assign('follow_log', $follow_log);
        $this->display();
    }



    public function dealer_pay_follow(){
        $order_id = I('post.order_id/d');
        if ($order_id < 1) {
            $this->helpJsonResult(410, "参数错误，拍单ID不能为空");
        }
        $o = new AuOrder($order_id);
        $order = $o->detail();
        if ($order['is_lock'] == 1) {
            $this->helpJsonResult(500, "拍单已锁定");
        }
        $car_id = I("post.car_id/d");
        if ($car_id < 1) {
            $this->helpJsonResult(408, "汽车ID错误");
        }
        $remark = I('post.remark');
        $pay_log = array();
        $pay_log['order_id'] = $order_id;
        $pay_log['emp_id'] = $this->user_info['emp_id'];
        $pay_log['remark'] = $remark;
        $pay_log['createtime'] = date("Y-m-d H:i:s", time());

        M()->startTrans();
        \AuctionCore\AuctionOrder\AuOrder::save_dealer_pay_follow_log($pay_log);
        //记录员工操作日志
        $log = array(
            'emp_id' => $this->user_info['emp_id'],
            'order_id' => $order_id,
            'car_id' => $car_id,
            'action' => '车商付款继续跟踪,继续跟踪备注'
        );
        \AuctionCore\System\SystemLog::add($log);
        M()->commit();

        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => "车商付款跟踪",
            'emp_id' => $this->user_info['emp_id']
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($car_id, $car_action_data);
        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => "车商付款跟踪",
            'emp_id' => $this->user_info['emp_id']
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);

        $this->helpJsonResult(200, "确认成功");
    }

    /**
    * 车商付款违约
    */
    public function dealer_pay_violate(){
        $order_id = I('post.order_id');
        $dealer_id = I('post.dealer_id');
        $remark = I('post.violate_remark');
        if ($remark == '') {
            $this->helpJsonResult(500, "请填写争议备注信息");
        }
        $o = new AuOrder($order_id);
        $order = $o->detail();
        if ($order['is_lock'] == 1) {
            $this->helpJsonResult(500, "拍单已锁定");
        }
        $proceeds_log = array();
        $proceeds_log['order_id'] = $order_id;
        $proceeds_log['emp_id'] = $this->user_info['emp_id'];
        $proceeds_log['remark'] = $remark;
        $proceeds_log['violatetime'] = date('Y-m-d H:i:s');
        $params = array();
        // 获取表单信息
        $params['order_id'] = $order_id; 
        $params['dealer_id'] = $dealer_id;
        // 业务处理
        $res = \AuctionCore\CarResource\CarCheck::dealer_pay_issue($params,$proceeds_log);
        if (!$res) {
            $msg = '确认失败或已确认,数据未更新。';
            $this->helpJsonResult(500, $msg);
        }
        $o = new AuOrder($order_id);
        $order_detail = $o->detail();
        //记录员工操作日志
        $log = array(
            'emp_id' => $this->user_info['emp_id'],
            'order_id' => $order_id,
            'action' => '车商付款跟踪,付款超时'
        );
        \AuctionCore\System\SystemLog::add($log);

        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => "车商付款超时",
            'emp_id' => $this->user_info['emp_id']
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($order_detail['car_id'], $car_action_data);
        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => "车商付款超时",
            'emp_id' => $this->user_info['emp_id']
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);
        $this->helpJsonResult(200, "确认成功");
    }


    /**
     * 违约查看
     */
    public function pay_info()
    {
        $order_id = I('request.order_id/d');
        $order = new AuOrder($order_id);
        $order_detail = $order->owner_confirm_detail();
        //车源信息
        $c = new Car($order_detail['car_id']);
        $car = $c->detail();
        $car['emission'] = C('EMISSION.' . $car['emission']);
        $addr = new \AuctionCore\Other\Address();
        $car['reg_city'] = $addr->get_name_by_code($car['reg_city']);
        $car['pointer_mileage'] = $car['pointer_mileage']/10000;
        $prefix = C('DB_PREFIX');
        $car_detail = M('cars')->alias('c')->field('c.*,co.comefrom,co.comefrom_url')
            ->join(" LEFT JOIN " . C('DB_PREFIX') . "car_owner as co ON c.`owner_id`=co.`owner_id`")
            ->where(array('car_id' => $order_detail['car_id']))->find();
        $location_area = $addr->get_name_by_code($car_detail['location_area']);
        $car_detail['location_area'] = $location_area;
        $this->assign('car_detail', $car_detail);
        $show_from = get_from();  //获取渠道来源信息
        $this->assign('show_from', $show_from);
        $transfer_type = C('TRANSFER_LIMIT');
        $sql = "SELECT d.contact_person,du.uid,apl.createtime,apl.violatetime,apl.remark,e.real_name
                FROM {$prefix}order ao
                LEFT JOIN {$prefix}dealer_auctioned as ada ON (ao.order_id=ada.order_id AND ada.`status`=0)
                LEFT JOIN {$prefix}car_dealer d ON ada.dealer_id = d.dealer_id
                LEFT JOIN {$prefix}dealer_user du ON du.dealer_id = d.dealer_id
                LEFT JOIN {$prefix}proceeds_log apl ON apl.order_id = ao.order_id
                LEFT JOIN {$prefix}employee e ON apl.emp_id = e.emp_id
                WHERE ao.order_id='{$order_id}' ";
        $info = M()->query($sql)[0];
        $dealer = new Dealer();
        $info = $dealer->get_contact_mobile_byAntNestfind($info);
        $this->assign('info', $info);
        //收款明细
        $collect_detail = collection::get_dealer_pay_detail($order_id);
        $this->assign('collect_detail', $collect_detail);
        $this->assign('transfer_type', $transfer_type);
        $this->assign('order', $order_detail);
        $this->assign('car', $car);
        $this->display();
       
    }


    private function record_log($order_id, $car_id, $action)
    {
        //记录员工操作日志
        $log = [
            'emp_id' => $this->emp_id,
            'order_id' => $order_id,
            'car_id' => $car_id,
            'owner_id' => 0,
            'action' => $action
        ];
        \AuctionCore\System\SystemLog::add($log);

        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => $action,
            'emp_id' => $this->emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($car_id, $car_action_data);

        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => $action,
            'emp_id' => $this->emp_id
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);
    }


        //违约
    public function violate(){
        $order_id = I("post.order_id/d", 0);
        if ($order_id < 1) {
            $this->helpJsonResult(400, "参数错误");
        }
        $o = new AuOrder($order_id);
        $orderInfo = $o ->detail();
        if ($orderInfo['is_lock'] == 1) {
            $this->helpJsonResult(400, "拍单已锁定");
        }
        $poInfo = $o->getPurchaseByOrderId();
        $c = new Car($orderInfo['car_id']);
        $carInfo = $c ->detail();
        $car_plate_number = C('PLATE_PREFIX')[$carInfo['plate_prefix']] . $carInfo['plate_suffix'];
        $data = [];
        $data['order_id'] = $order_id;
        $data['order_no'] = $orderInfo['order_no'];
        $data['po_id'] = $poInfo['id'];
        $data['sid'] = $poInfo['sid'];
        $data['po_no'] = $poInfo['purchase_order_nu'];
        $data['car_plate_number'] = $car_plate_number;
        $data['order_status'] = $orderInfo['status'];
        $data['source'] = 5;
        $data['originator'] = $this->emp_id;
        $res = ChangeOrder::CreateChangeOrder($data);
        if(!$res){
            $this->record_log($order_id, $orderInfo['car_id'], "车商付款跟踪发起违约");
            $this->helpJsonResult(400, '处理失败');
        }else{
            $this->helpJsonResult(200, '处理成功');
        }
    }

}
